package com.colter.project.sample.thread.part02.test1;

import java.util.Date;
import java.util.LinkedList;

//生产者 消费者  同步代码块中使用条件  wait notify
public class Test3 {
	public static void main(String[] args) {
		EvenStorage storage = new EvenStorage();
		Producer producer = new Producer(storage);
		Consumer consumer = new Consumer(storage);
		Thread t1 = new Thread(producer);
		Thread t2 = new Thread(consumer);
		t2.start();
		t1.start();

	}
}

class EvenStorage {
	private int max;
	private LinkedList<Object> list;

	public EvenStorage() {
		max = 10;
		list = new LinkedList<>();
	}

	public synchronized void set() {
		while (list.size() == max) {
			try {
				wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		list.add(new Date());
		System.out.println("Set:" + list.size());
		
		try {
			Thread.sleep(300);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		notifyAll();
	}

	public synchronized void get() {
		while (list.size() == 0) {
			try {
				wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}

		System.out.println("Get:" + list.size() + " " + list.poll());
		
		try {
			Thread.sleep(300);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		notifyAll();
	}
}

class Producer implements Runnable {
	
	public Producer(EvenStorage storage) {
		super();
		this.storage = storage;
	}

	private EvenStorage storage;

	@Override
	public void run() {
		for (int i = 0; i < 100; i++) {
			storage.set();
		}
	}

}

class Consumer implements Runnable {
	
	
	public Consumer(EvenStorage storage) {
		super();
		this.storage = storage;
	}

	private EvenStorage storage;

	@Override
	public void run() {
		for (int i = 0; i < 100; i++) {
			storage.get();
		}
	}
}
